<script setup>
import api from '../api/review_api.js'  // 注意修改为 Review 接口路径
import attractionApi from '../api/attraction_api.js'  // 导入景点API
import { ref, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import lodash from 'lodash'

// 数据定义区域
const tableData = ref([]);
const total = ref(0);
const editWinVisible = ref(false);
const attractionSelectVisible = ref(false); // 景点选择弹窗
const attractions = ref([]); // 景点列表

const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  attraction_name: '',
  username: '',
  attraction_id: '',
  rating: ''
});

const obj = ref({});

// 查询方法
const search = async () => {
  const result = await api.pageWithDetails(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
};

// 获取所有景点用于选择
const loadAttractions = async () => {
  try {
    const result = await attractionApi.page({ current: 1, limit: 9999 });
    attractions.value = result.data || [];
  } catch (error) {
    console.error('获取景点列表失败:', error);
    ElMessageBox.alert('获取景点列表失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
  }
};

// 选择景点
const selectAttraction = (attraction) => {
  obj.value.attraction_id = attraction.id;
  obj.value.attraction_name = attraction.name; // 临时存储景点名称用于显示
  attractionSelectVisible.value = false;
};

// 取消选择景点
const cancelSelectAttraction = () => {
  attractionSelectVisible.value = false;
};

onMounted(async () => {
  await search();
});

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};
// 当前登录用户信息
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
});
const editCommit = async () => {
  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    await api.add(obj.value);
  }
  search();
  editWinVisible.value = false;
};

const handleSearch = () => {
  searchObj.value.current = 1;
  search();
};

const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};

const handleAdd = async () => {
  obj.value = {
    user_id: loginUser.value.id, // 默认为当前用户
    attraction_id: '',
    attraction_name: '', // 添加景点名称字段用于显示
    rating: 0, // 默认评分为0
    comment: ''
  };
  await loadAttractions(); // 加载景点列表
  editWinVisible.value = true;
};

const handleEdit = (index, row) => {
  // 检查是否是管理员或评论创建者
  if (isAdminLogin() || isOwner(row.user_id)) {
    obj.value = lodash.clone(row);
    // 添加景点名称用于显示
    if (row.attraction_name) {
      obj.value.attraction_name = row.attraction_name;
    }
    editWinVisible.value = true;
  } else {
    ElMessageBox.alert('您只能编辑自己的评论！', '权限提示', {
      type: 'warning'
    });
  }
};

const handleDelete = (index, row) => {
  // 检查是否是管理员或评论创建者
  if (isAdminLogin() || isOwner(row.user_id)) {
    ElMessageBox.confirm(
        '确认删除该评论吗？',
        '删除提示',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'error'
        }
    )
        .then(async () => {
          await api.del(row.id);
          searchObj.value.current = 1;
          search();
        })
        .catch(() => {});
  } else {
    ElMessageBox.alert('您只能删除自己的评论！', '权限提示', {
      type: 'warning'
    });
  }
};

// 判断当前用户是否是评论创建者
const isOwner = (reviewUserId) => {
  return  parseInt(loginUser.value.id) === parseInt(reviewUserId);
};

const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}
</script>

<template>
  <div class="review-management-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchObj" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="景点名">
        <el-input v-model="searchObj.attraction_name" placeholder="请输入景点名" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="评分">
        <el-input v-model="searchObj.rating" placeholder="请输入评分" clearable style="width: 150px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item v-if="!isAdminLogin()">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 评论表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
    >
<!--      <el-table-column label="ID" width="80" align="center">-->
<!--        <template #default="scope">-->
<!--          {{ scope.row.id }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="用户名" min-width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="景点名" min-width="120">
        <template #default="scope">
          {{ scope.row.attraction_name }}
        </template>
      </el-table-column>
      <el-table-column label="评分" min-width="100">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.rating }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评论内容" min-width="250">
        <template #default="scope">
          {{ scope.row.comment }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" align="center">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              style="margin-left: 5px;"
              :disabled="!isAdminLogin() && !isOwner(scope.row.user_id)"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin-left: 5px;"
              :disabled="!isAdminLogin() && !isOwner(scope.row.user_id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" :title="obj.id ? '编辑评论信息' : '新增评论信息'" width="600px">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
        <el-form-item label="用户ID" v-if="isAdminLogin()">
          <el-input v-model="obj.user_id" autocomplete="off" />
        </el-form-item>
        <el-form-item label="当前用户" v-else>
          <el-input :value="loginUser.id" disabled />
        </el-form-item>
        <el-form-item label="景点">
          <el-input
            v-model="obj.attraction_name"
            autocomplete="off"
            disabled
            v-if="obj.attraction_name"
          />

          <div style="margin-top: 10px;">
            <el-button type="primary" @click="loadAttractions().then(() => attractionSelectVisible = true)">
              {{ obj.attraction_id ? '重新选择景点' : '选择景点' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="评分">
          <el-rate
            v-model="obj.rating"
            :max="5"
            allow-half
            show-score
            score-template="{value}分"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input type="textarea" v-model="obj.comment" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit" :disabled="!obj.attraction_id">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 景点选择对话框 -->
    <el-dialog v-model="attractionSelectVisible" title="选择景点" width="800px">
      <el-table :data="attractions" height="400" @row-click="selectAttraction" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="景点名称" min-width="150"></el-table-column>
        <el-table-column prop="city" label="城市" min-width="120"></el-table-column>
        <el-table-column prop="type" label="类型" min-width="120"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSelectAttraction">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
